//
//  FMDatabase+Database.m
//  News
//
//  Created by xalo on 16/3/2.
//  Copyright © 2016年 News. All rights reserved.
//

#import "FMDatabase+Database.h"
#import "NewsModel.h"

#import "VideoModel.h"

#import "DetialModel.h"


@implementation FMDatabase (Database)

#pragma mark - 数据库单例
//单例存放数据缓存
static FMDatabase *db = nil;
+ (id)shareManager {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        //打开数据库
        NSString *path = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject;
        NSString *filePath = [path stringByAppendingPathComponent:@"news.sqlite"];
        db = [FMDatabase databaseWithPath:filePath];
        [db open];
        
        //创建缓存表
        [db executeUpdate:@"CREATE TABLE IF NOT EXISTS 'news_caches' (id INTEGER primary key,newsModelArray blob NOT NULL,channel TEXT NOT NULL);"];
        

        //创建收藏表
        [db executeUpdate:@"CREATE TABLE IF NOT EXISTS 'news_collection' (id TEXT PRIMARY KEY,newsModel blob NOT NULL,category TEXT NOT NULL);"];
        
     
       
       
    });
    return db;
}

#pragma mark - 缓存表
// 数据库存储网络请求的数据
- (void)saveModel:(NSArray *)newsModelArray withChannel:(NSString *)channel {
    
    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:newsModelArray];
    
    [db executeUpdateWithFormat:@"INSERT INTO 'news_caches'(newsModelArray,channel) VALUES(%@,%@);",data,channel];
}

// 根据参数查询
- (NSArray *)selectNewsModelArrayWithChannel:(NSString *)channel times:(NSInteger)times {
    
    NSMutableArray *newsModelArray = [NSMutableArray array];
    FMResultSet *set = [db executeQueryWithFormat:@"SELECT * FROM news_caches where channel=%@ ORDER BY id ASC;",channel];
    while (set.next) {
        
        NSData *data = [set objectForColumnName:@"newsModelArray"];
        
        NSArray *array = [NSKeyedUnarchiver unarchiveObjectWithData:data];
        [newsModelArray addObject:array];
    }
    return (newsModelArray.count == 0 || times > newsModelArray.count-1)? nil : newsModelArray[times];
}

// 根据子标题,删除数据库中对应的所有数据
- (void)deleteNewsModelArrayByChannel:(NSString *)channel {
    
    [db executeUpdateWithFormat:@"DELETE FROM news_caches WHERE channel=%@;",channel];
    
}

#pragma mark - 收藏表
// 存储需要收藏的newsModel
- (void)saveCollectionModel:(NewsModel *)newsModel withID:(NSString *)ID {
    
    NSMutableData *data = [NSMutableData data];
    
    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
    
    [archiver encodeObject:newsModel forKey:@"newsModel"];
    
    [archiver finishEncoding];
    
    [db executeUpdateWithFormat:@"INSERT INTO 'news_collection'(id,newsModel,category) VALUES(%@,%@,%@);",ID,data,newsModel.category];
    
}

// 查询收藏表中的所有数据
- (NSArray *)selectAllCollection {
    

    NSMutableArray *array = [NSMutableArray array];
    FMResultSet *set = [db executeQuery:@"SELECT * FROM 'news_collection';"];
    while (set.next) {
        
        NSData *data = [set objectForColumnName:@"newsModel"];
        NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
        NewsModel *model = [unarchiver decodeObjectForKey:@"newsModel"];

        
//        [array addObject:model];
    }
    return array;
}

// 根据分类查询数据
- (NSArray *)selectCollectionByCategory:(NSString  *)category {
    
    NSMutableArray *array = [NSMutableArray array];
    FMResultSet *set = [db executeQueryWithFormat:@"SELECT * FROM 'news_collection' WHERE category=%@",category];
    if ([category isEqualToString:@"cms"]) {
        //新闻
        while (set.next) {
            NSData *data = [set objectForColumnName:@"newsModel"];
            NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
            NewsModel *model = [unarchiver decodeObjectForKey:@"newsModel"];
            [array addObject:model];
        }
    }else if ([category isEqualToString:@"video"]){
        // 视频分类
        while (set.next) {
            NSData *data = [set objectForColumnName:@"newsModel"];
            NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
            VideoModel *model = [unarchiver decodeObjectForKey:@"videoModel"];
            [array addObject:model];
        }
        
    }else if ([category isEqualToString:@"Model"]){
        //图片
            FMResultSet *set = [db executeQueryWithFormat:@"select * from 'news_collection' where category=%@",@"Model"];
        
        while (set.next) {
            
            NSData *data = [set objectForColumnName:@"newsModel"];
            
            NSArray *arr = [NSKeyedUnarchiver unarchiveObjectWithData:data];
            
            [array addObject:arr];
            
             }
        
        }
    return array;
}


#pragma mark - 图片
- (void)saveCollectionOtherModel:(NSArray *)newsModel withID:(NSString *)ID {
     
    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:newsModel];
    
    [db executeUpdateWithFormat:@"INSERT INTO 'news_collection'(id,newsModel,category) VALUES(%@,%@,%@);",ID,data,@"Model"];
    
}

-(NSArray *)selectOtherCollection {
    
    NSMutableArray *array = [NSMutableArray array];
    
    FMResultSet *set = [db executeQueryWithFormat:@"select * from 'news_collection' where category=%@",@"Model"];
    
    while (set.next) {
        
        NSData *data = [set objectForColumnName:@"newsModel"];
        
        NSArray *arr = [NSKeyedUnarchiver unarchiveObjectWithData:data];

        [array addObject:arr];
        
    }
    
    return array;
    
}





// 根据ID删除收藏表中的newsModel
- (void)removeCollectionModelByID:(NSString *)ID {
    
    [db executeUpdateWithFormat:@"DELETE FROM 'news_collection' WHERE id=%@;",ID];
}


//收藏video
- (void)collectVideModel:(VideoModel *)videoModel {


    
    NSMutableData *data = [NSMutableData data];
    
    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
    
    [archiver encodeObject:videoModel forKey:@"videoModel"];
    
    [archiver finishEncoding];
    
    [db executeUpdateWithFormat:@"INSERT INTO 'news_collection'(id,newsModel,category) VALUES(%@,%@,%@);",videoModel.ID,data,videoModel.category];

}



-(NSArray *)showCollectedVideoModel {

    
    NSMutableArray *array = [NSMutableArray array];
    FMResultSet *set = [db executeQuery:@"SELECT * FROM 'news_collection';"];
    while (set.next) {
        
        NSData *data = [set objectForColumnName:@"newsModel"];
        NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
        VideoModel *model = [unarchiver decodeObjectForKey:@"videoModel"];
//        [array addObject:model];
    }
    return array;

}

//-(NSArray *)showCollectedVideoModel {
//
//    
//    NSMutableArray *array = [NSMutableArray array];
//    FMResultSet *set = [db executeQuery:@"SELECT * FROM 'news_collection';"];
//    while (set.next) {
//        
//        NSData *data = [set objectForColumnName:@"newsModel"];
//        NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
//        VideoModel *model = [unarchiver decodeObjectForKey:@"videoModel"];
//        [array addObject:model];
//    }
//    return array;
//
//}








@end
